<template>
  <!-- 绑定模板（危险源绑定、WBS绑定） -->
  <div class="BindingTemplate-container">
    <div class="left-panel">
      <div class="left-panel-header header">
        <span class="title">已选模型</span>
      </div>
      <div class="left-panel-body">
        <a-spin :spinning="loading.isTable">
        <div class="model-item" v-for="(item, index) in modelList" :key="item.id">
          <span class="item-content">{{ item.name }}</span>
          <a-icon type="close" class="item-btn base-btn" @click="handleModelItem('delete', index)" />
        </div>
        </a-spin>
      </div>
    </div>
    <div class="right-panel">
      <div class="right-panel-header header">
        <span class="title">{{ bindType | filterBindType}}绑定</span>
        <div class="select-row" >
          <span class="row-name" v-show="selectData.id">{{ selectData.name }}</span>
          <span class="row-state" :class="selectData.hasBind ? 'fc-blue' : 'fc-red'" v-show="selectData.id">{{
            selectData.hasBind ? '已绑定' : '未绑定'
          }}</span>
        </div>
        <a-button type="primary" @click="handleBindModel" :loading="loading.isBinding" :disabled="!selectData.id">绑定模型</a-button>
      </div>
      <div class="right-panel-body">
        <a-table
          :rowKey="(record) => record.id"
          :columns="columns"
          :data-source="tableList"
          :customRow="customRowFn"
          :pagination="false"
          :scroll="{ y: 400 }"
          :loading="loading.isTable"
        >
          <template slot="hasBind" slot-scope="text, record">
            <span :class="record.hasBind ? 'fc-blue' : 'fc-red'" v-if="selectLevel === null || record.level === selectLevel">{{ record.hasBind ? '已绑定' : '未绑定' }}</span>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
import { getWbsWithModel, getCriticalWithModel, bindModelWithProject, updateBindBatch } from '@/api/bimIntegrate/business'
const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '绑定状态',
    dataIndex: 'hasBind',
    key: 'hasBind',
    scopedSlots: { customRender: 'hasBind' },
  },
  {
    title: '绑定构件',
    dataIndex: 'bindingModel',
    key: 'bindingModel'
  },
]
export default {
  props: {
    modelId: {
      type: String,
      default: ''
    },
    bindType: {
      required: true,
      type: String,
      default: '',
    },
    selectLevel: { // 允许选择的节点层级，默认null为每一层都可以选择
      type: [Number, Object],
      default: null
    }
  },
  filters: {
    filterBindType(type) {
      const map = {
        'wbs': 'WBS',
        'critical': '危大工程'
      }
      return map[type] || ''
    }
  },
  data() {
    return {
      loading: {
        isTable: false,
        isBinding: false
      },
      selectData: {
        name: '',
        hasBind: false,
      },
      columns: columns,
      tableList: [],
      modelList: [], // 已选模型列表
    }
  },
  watch: {
    modelId: {
      handler(val) {
        if(!val) return
        this.getListWithModel()
      }
    }
  },
  created() {
    this.getListWithModel()
  },
  methods: {
    async handleBindModel() {
      const { hasBind, id } = {...this.selectData}
      if(!id) {
        this.$message.error('请选择绑定对象')
        return
      }
      if(this.loading.isBinding) return
      this.loading.isBinding = true
      const fn = hasBind ? updateBindBatch : bindModelWithProject // 区分新增、修改
      const typeMap = { //  PROJECT, WBS, DANGER_PROJECT
        'wbs': 'WBS',
        'critical': 'DANGER_PROJECT'
      }
      const params = {
        model: false, // true为模型，false为构件(在此处绑定的都是构件)
        businessId: id,
        models: this.modelList.map(item => {
          return {
            modelId: item.name,
            modelName: item.name
          }
        }),
        parentId: this.modelId,
        type: typeMap[this.bindType]
      }
      const [err, res] = await fn(params)
      this.loading.isBinding = false
      if(!err) {
        this.$message.success('绑定成功')
        this.getListWithModel()
      }
    },
    // 获取绑定列表
    async getListWithModel() {
      if(!this.modelId) return
      const params = {
        modelId: this.modelId,
      }
      const fnMap = {
        'wbs': getWbsWithModel,
        'critical': getCriticalWithModel
      }
      const fn = fnMap[this.bindType] || ''
      if(!fn) return
      if(this.loading.isTable) return
      this.loading.isTable = true
      const [err, res] = await fn(params)
      this.loading.isTable = false
      this.modelList = [] // 清空所选数据
      this.selectData = {}
      if (!err) {
        if(Array.isArray(res.data)) { // wbs 和危大工程返回的结构不同
          this.tableList = res.data
        } else {
          this.tableList = res.data && [res.data] || []
        }
      } else {
        this.tableList = []
      }
    },
    // 表格自定义行操作
    customRowFn(record) {
      return {
        on: {
          click: (e) => {
            if(this.selectLevel !== null && record.level !== this.selectLevel) {
              this.selectData = {}
              return
            }
            this.selectData = { ...record }
            if(this.selectData.bindingModelIds) {
              // 将已绑定的构件，回显到左侧已选模型列表中
              const bindingModelNames = this.selectData.bindingModel && this.selectData.bindingModel.split('/') || []
              const result = []
              this.selectData.bindingModelIds.forEach((item,index) => {
                result.push({
                  id: item,
                  name: bindingModelNames[index] || ''
                })
              })
              this.modelList = result
            }
          },
        },
      }
    },
    handleModelItem(type, index, data = {}) {
      if (type === 'delete') {
        this.modelList.splice(index, 1)
      }
      if (type === 'add') {
        const existIndex = this.modelList.findIndex((item) => item.id === data.id)
        if (existIndex === -1) {
          this.modelList.push(data)
        }
      }
    },
  },
}
</script>

<style lang="less" scoped>
.BindingTemplate-container {
  background-color: #ffffff;
  width: 100%;
  height: 100%;
  padding: 0 20px;
  color: rgba(127, 127, 127, 1);
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  .left-panel,
  .right-panel {
    width: 48%;
    .header {
      padding: 12px 0;
      border-bottom: 1px solid rgba(225, 225, 225, 1);
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      .title {
        font-size: 16px;
        line-height: 32px;
        color: #000000;
      }
      .select-row {
        flex: 1;
        padding: 0 10px;
        display: flex;
        justify-content: center;
        .row-state {
          margin-left: 12px;
        }
      }
    }
  }
  .left-panel-body {
    overflow: auto;
    .model-item {
      display: flex;
      padding: 10px;
      .item-content {
        flex: 1;
      }
      .item-btn {
        width: fit-content;
      }
    }
  }
  .fc-red {
    color: red;
  }
  .fc-blue {
    color: #1890ff;
  }
}
</style>